package com.scalar.chiptrack.adaptor.ikanos.fab;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.InventoryLot;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.utils.ParserResult;
import com.scalar.chiptrack.adaptor.utils.Parser;
import com.scalar.chiptrack.adaptor.utils.ParserFactory;
import com.scalar.chiptrack.adaptor.utils.XLSParserImpl;
import com.scalar.chiptrack.adaptor.dao.InventoryLotDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.db.DataSource;
import com.scalar.ScalarException;

import java.util.HashMap;
import java.util.ArrayList;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 21 Sep, 2010
 * Time: 6:41:47 PM
 * To change this template use File | Settings | File Templates.
 */
public class FabInvoiceDataParser extends JobHandler implements AdaptorConstants
{
    private Logger m_parserLogger       = null;
    private String m_dataOutputDir      = null;

    public FabInvoiceDataParser() throws ScalarException
    {
        try
        {
            m_dataOutputDir = ConfigManager.getInvoicePortingFileDir();

            if ( m_dataOutputDir != null )
            {
                AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );

                m_parserLogger= AdaptorUtils.getDataParserLogger( m_dataOutputDir,"INVOICE" );

                AdaptorUtils.setLogger( m_parserLogger );
                InventoryLotDAO.setLogger(m_parserLogger);
            }
        }
        catch ( Exception se )
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while loading INVOICE output directory details from database, Exception: " + se );
            System.out.println( "ERROR!! ERROR!! ERROR!! Exception while loading INVOICE output directory details from database, Exception: " + se );
        }
    }

    public static void main( String args[] ) throws Exception
    {
        try
        {
            new FabInvoiceDataParser().execute();
        }
        catch ( Exception e )
        {
            throw e;
        }
    }
    public void execute() throws Exception
    {
        AdaptorUtils.printHeader( "INVOICE", CONSTANT_PARSER );

        File doneDestDir = new File( m_dataOutputDir + "/done" );
        File dataoutDir  = new File( m_dataOutputDir );

        File[] fileList = dataoutDir.listFiles();

        if ( ( fileList == null ) || (fileList.length <= 3))
        {
            log("No file found in directory: " + dataoutDir);
            System.out.println("No file found in directory: " + dataoutDir );
            throw new ScalarException("No file found in directory: " + dataoutDir+ "----\n\n" );
        }

        ArrayList<File> successFileList = new ArrayList<File>();

        boolean success = false;

        for ( int i = 0; i < fileList.length; i++ )
        {
            if ( fileList[i].isDirectory() == true )
            {
                continue;
            }

            try
            {
                if ( fileList[i].getName().startsWith( FabInvoiceAdaptor.FILE_NAME )  || fileList[i].getName().indexOf( FabInvoiceAdaptor.FILE_NAME )  != -1)
                {
                     parseInvoiceReport( fileList[i].getAbsolutePath() );

                    successFileList.add(fileList[i]);
                }

               success = true;
            }
            catch (Exception e)
            {
                success = false;
                log("Exception while parsing file: " + fileList[i].getAbsolutePath() + "\nException: " + e);
                e.printStackTrace();
                throw e;
            }
        }
        int adaptor_id = AdaptorRunInfo.getLastRunAdaptorId( FabInvoiceAdaptor.ADAPTOR_NAME, CONSTANT_ADAPTOR);
        // transaction 9
        try
        {
            if (success)
            {
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, FabInvoiceAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
                System.out.println("SUCCESSFULLY UPDATED IN THE DATABASE");
            }
        }
        catch (ScalarException se)
        {
            success = false;  //As filES DATA SAVED , UPDATEING AS SUCCESS
            AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, FabInvoiceAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
            log("WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se);
            throw se;
        }

        // Step 10
        // Move the successful files to 'done' directory
        if (success)
        {
            AdaptorUtils.moveFilesToDone( successFileList, doneDestDir);
        }
    }

    private void parseInvoiceReport (String fileName ) throws Exception
    {
        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );

        ParserResult result            = null;

        File detailWipFile = new File( fileName );
        if ( !detailWipFile.exists() )
        {
            throw new ScalarException( fileName + " doesnt exist" );
        }

        Parser parser = ParserFactory.getXLSParser( detailWipFile );

        log( "\nFound " + fileName );
        log( "\nParsing the file for Invice Report..." );
        System.out.println( "\nFound " + fileName );
        System.out.println( "\nParsing the file for Invice Report..." );

        Connection conn         = null;
        PreparedStatement pstmt = null;
        boolean success = false;

        conn = DataSource.getConnection();

        ((XLSParserImpl)parser).setHeaderRowIdx(0);
        ((XLSParserImpl)parser).setDataStartRowIdx(1);
        try
        {
            pstmt = conn.prepareStatement( " { CALL sp_create_update_Fab_Invoice_Cost (?, ?, ?, ? ) }" );
            result = parser.parse();
            //System.out.println("result = " + result.getHeadings() );
            while ( result.next() )
            {
                if ( result.getString ( "Cust_Prod_Code" ) != null && result.getString ( "Cust_Prod_Code" ).trim().length() > 0  )
                {   String partNo = null;
                    if ( result.getString ( "Cust_Prod_Code" ).indexOf("-") != -1 )
                    {
                       partNo =   result.getString ( "Cust_Prod_Code" ).substring(0, result.getString ( "Cust_Prod_Code" ).indexOf("-") );
                    }
                    else
                    {
                        partNo = result.getString ( "Cust_Prod_Code" ).trim();
                    }

                    if (result.getDouble ( "Wafer Cost" ) > 0.0 )
                    {
                        pstmt.setString( 1, partNo );
                        pstmt.setString( 2, result.getString ( "Lot_No" ) );
                        pstmt.setDouble( 3, result.getDouble ( "Wafer Cost" ) );
                        pstmt.setString( 4, result.getString ( "Vendor" ) );

                        pstmt.addBatch();
                    }
                }
                else
                {
                    //System.out.println ( "IN ELSE " + result.getString ( "Wafer Part" ) + ":" +  result.getString ( "Sort" )  );
                }
            }
            pstmt.executeBatch();

            success = true;
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {

            try
            {
                if (conn != null)
                {
                    if( success == true )
                    {
                        conn.commit();
                    }
                    else
                    {
                        conn.rollback();
                    }
                }
            }
            catch (SQLException ignore) {System.out.println("Sql exception ");}

            if ( pstmt != null )
            {
                try { pstmt.close(); } catch (SQLException ignore){}
            }
            if ( conn != null )
            {
                try { conn.close(); } catch (SQLException ignore){}
            }
        }
    }

    private void log( String message )
    {
      if ( message == null ) return;

      if ( m_parserLogger != null )
      {
          m_parserLogger.logDebug( message + LINE_SEPARATOR );
      }
      else
      {
          System.out.println( message );
      }
    } // end of log method

}
